package com.sgb.kjwl.view.ui.fragment.self.mine

import android.content.res.Resources
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider
import com.sgb.kjwl.AppLazyFragment
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.FragmentUserOrganizationAttentionBinding
import com.sgb.kjwl.databinding.ItemGroupAttentionBinding
import com.sgb.kjwl.databinding.ItemOrganizationAttentionBinding
import com.sgb.kjwl.databinding.ItemUserAttentionBinding
import com.sgb.kjwl.di.self.DaggerSelfFragComponent
import com.sgb.kjwl.di.self.SelfFragModule
import com.sgb.kjwl.model.entity.self.SelfAttentionEntity
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity
import com.sgb.kjwl.viewmodel.self.mine.AttentionViewModel
import com.swgk.core.base.di.AppComponent
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration
import com.swgk.core.util.ClickUtils
import com.swgk.core.util.MToast
import javax.inject.Inject


class UserOrganizationAttentionFragment : AppLazyFragment(){
    private lateinit var mBinding : FragmentUserOrganizationAttentionBinding
    private var isLoadMore = false //是否加载更多
    private var isEnableLoadMore = false//是否能加载更多

    private lateinit var mUserAdapter : UserAttentionAdapter

    private lateinit var mGroupAdapter : GroupAttentionAdapter

    private lateinit var mOrganizationAdapter : OrganizationAttentionAdapter

    private var mAttentionType : Int = TYPE_PERSON

    @Inject
    lateinit var mViewModel : AttentionViewModel

    companion object {
        const val KEY_TYPE = "key_type"
        const val TYPE_PERSON = 0
        const val TYPE_GROUP = 2
        const val TYPE_ORGANIZATION = 3
        fun newInstance(type : Int): UserOrganizationAttentionFragment {
            val args = Bundle()
            val fragment = UserOrganizationAttentionFragment()
            args.putInt(KEY_TYPE, type)
            fragment.arguments = args
            return fragment
        }
    }

    override fun onLazyLoad() {
        isLoadMore = false
        getDatas()
    }

    private fun getDatas(){
        if (mAttentionType == TYPE_PERSON){
            mViewModel.getUserAttentionList(requireContext(), isLoadMore)
        } else if (mAttentionType == TYPE_GROUP){
            mViewModel.getGroupAttentionList(requireContext(), isLoadMore)
        } else if (mAttentionType == TYPE_ORGANIZATION){
           mViewModel.getOrganizationAttentionList(isLoadMore)
        }
    }

    override fun setupFragmentComponent(appComponent: AppComponent?) {
        super.setupFragmentComponent(appComponent)
        DaggerSelfFragComponent.builder().appComponent(appComponent)
            .selfFragModule(SelfFragModule()).build().inject(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (arguments != null){
            mAttentionType = requireArguments().getInt(KEY_TYPE)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_user_organization_attention, container, false)
        return mBinding.root
    }

    override fun initView() {
        super.initView()
        mBinding.recyclerView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        // SwipeRefreshLayout 刷新
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                mBinding.refreshLayout.finishLoadMore(500)
                getDatas()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isLoadMore = false
                mBinding.refreshLayout.finishRefresh(500)
                getDatas()
            }
        })
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        mBinding.refreshLayout.setScrollBoundaryDecider(object : ScrollBoundaryDecider {
            override fun canRefresh(content: View): Boolean {
                if (mBinding.recyclerView == null) return false
                return mBinding.recyclerView.computeVerticalScrollOffset() === 0
            }

            override fun canLoadMore(content: View): Boolean {
                if (mBinding.recyclerView == null) return false
                //整个View控件的高度
                val scrollRange: Int = mBinding.recyclerView.computeVerticalScrollRange()
                //当前屏幕之前滑过的距离
                val scrollOffset: Int = mBinding.recyclerView.computeVerticalScrollOffset()
                //当前屏幕显示的区域高度
                val scrollExtent: Int = mBinding.recyclerView.computeVerticalScrollExtent()
                //获取recyclerView的高度
                val height: Int = mBinding.recyclerView.height
                if (height > scrollRange) {
                    return false
                }
                return isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent
            }
        })
        val empty = LayoutInflater.from(context).inflate(R.layout.layout_empty_list, mBinding.recyclerView, false)
        empty.visibility = View.VISIBLE
        empty.findViewById<TextView>(R.id.no_data_tv).text = resources.getString(R.string.no_attention_list)
        empty.findViewById<TextView>(R.id.no_data_count).visibility = View.GONE
        if (mAttentionType == TYPE_PERSON){
            mUserAdapter = UserAttentionAdapter(R.layout.item_user_attention)
            mUserAdapter.bindToRecyclerView(mBinding.recyclerView)
            mUserAdapter.emptyView = empty
            mUserAdapter.setCallBack(object : AttentionCallBack{
                override fun cancelAttention(position: Int, entity: SelfAttentionEntity) {
                    if (!ClickUtils.isDoubleClick()) {
                        mViewModel.cancelUserAttention(context!!, entity.no, position)
                    }
                }

                override fun clickItem(entity: SelfAttentionEntity) {
                    if (!ClickUtils.isDoubleClick()){
                        WebsiteInfoActivity.start(context, entity.no, WebsiteInfoActivity.WEBSITE_FOR_PERSONAL)
                    }
                }

            })
        } else if (mAttentionType == TYPE_GROUP){
            mGroupAdapter = GroupAttentionAdapter(R.layout.item_group_attention)
            mGroupAdapter.bindToRecyclerView(mBinding.recyclerView)
            mGroupAdapter.emptyView = empty
            mGroupAdapter.setCallBack(object : AttentionCallBack{
                override fun cancelAttention(position: Int, entity: SelfAttentionEntity) {
                    if (!ClickUtils.isDoubleClick()) {
                        mViewModel.cancelGroupAttention(context!!, entity.no, position)
                    }
                }

                override fun clickItem(entity: SelfAttentionEntity) {
                    if (!ClickUtils.isDoubleClick()){
                        WebsiteInfoActivity.start(context, entity.no, WebsiteInfoActivity.WEBSITE_FOR_TEAM)
                    }
                }

            })
        } else if (mAttentionType == TYPE_ORGANIZATION){
            mOrganizationAdapter = OrganizationAttentionAdapter(R.layout.item_organization_attention, resources)
            mOrganizationAdapter.bindToRecyclerView(mBinding.recyclerView)
            mOrganizationAdapter.emptyView = empty
            mOrganizationAdapter.setCallBack(object : AttentionCallBack{
                override fun cancelAttention(position: Int, entity: SelfAttentionEntity) {
                    if (!ClickUtils.isDoubleClick()) {
                        mViewModel.cancelOrganizationAttention(entity.organizationNo, position)
                    }
                }

                override fun clickItem(entity: SelfAttentionEntity) {
                    if (!ClickUtils.isDoubleClick()){
                        WebsiteInfoActivity.start(context, entity.organizationNo, WebsiteInfoActivity.WEBSITE_FOR_ORGANIZE)
                    }
                }

            })
        }
        mBinding.recyclerView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        mBinding.recyclerView.addItemDecoration(
            RecyclerCustomDecoration(
                0f,
                0f,
                0f,
                resources.getDimension(R.dimen.dp1), resources.getColor(R.color.color_main_bg)
            )
        )
       renderLiveData()
    }

    fun renderLiveData(){
        mViewModel.mUserAttentionList.observe(this, {
            isEnableLoadMore = it != null && it.size >= 10
            if (isLoadMore){
                mUserAdapter.addData(it)
            } else {
                mUserAdapter.setNewData(it)
            }
        })
        mViewModel.mGroupAttentionList.observe(this, {
            isEnableLoadMore = it != null && it.size >= 10
            if (isLoadMore){
                mGroupAdapter.addData(it)
            } else {
                mGroupAdapter.setNewData(it)
            }
        })
        mViewModel.mOrganizationAttentionList.observe(this, {
            isEnableLoadMore = it != null && it.size >= 10
            if (isLoadMore){
                mOrganizationAdapter.addData(it)
            } else {
                mOrganizationAdapter.setNewData(it)
            }
        })
        mViewModel.mCancelGroup.observe(this, {
             if (it != -1) {
                 MToast.showToast(context, "取消关注成功")
                 mGroupAdapter.remove(it)
             }
        })
        mViewModel.mCancelUser.observe(this, {
            if (it != -1) {
                MToast.showToast(context, "取消关注成功")
                mUserAdapter.remove(it)
            }
        })
        mViewModel.mCancelOrganization.observe(this, {
            if (it != -1) {
                MToast.showToast(context, "取消关注成功")
                mOrganizationAdapter.remove(it)
            }
        })
    }


    class UserAttentionAdapter(layoutId : Int) : BaseQuickAdapter<SelfAttentionEntity, BaseViewHolder>(layoutId){
        private var mItemBinding : ItemUserAttentionBinding ?= null
        private var mCallBack : AttentionCallBack ?= null
        fun setCallBack(callBack : AttentionCallBack){
            this.mCallBack = callBack
        }
        override fun convert(helper: BaseViewHolder?, item: SelfAttentionEntity?) {
              mItemBinding = DataBindingUtil.bind(helper!!.itemView)
              if (mItemBinding != null){
                  mItemBinding!!.entity = item
                  mItemBinding!!.executePendingBindings()
                  Glide.with(mContext).load(item!!.headImg).error(R.mipmap.def_photo).placeholder(R.mipmap.def_photo).into(mItemBinding!!.ivUserPic)
                  mItemBinding!!.tvAttention.setOnClickListener {
                      if (mCallBack != null){
                          mCallBack!!.cancelAttention(helper.layoutPosition, item)
                      }
                  }
                  helper.itemView.setOnClickListener {
                      if (mCallBack != null){
                          mCallBack!!.clickItem(item)
                      }
                  }
              }
        }

    }

    class GroupAttentionAdapter(layoutId : Int) : BaseQuickAdapter<SelfAttentionEntity, BaseViewHolder>(layoutId){
        private var mCallBack : AttentionCallBack ?= null
        private var mItemBinding : ItemGroupAttentionBinding ?= null;
        fun setCallBack(callBack : AttentionCallBack){
            this.mCallBack = callBack
        }
        override fun convert(helper: BaseViewHolder?, item: SelfAttentionEntity?) {
            mItemBinding = DataBindingUtil.bind(helper!!.itemView)
            if (mItemBinding != null){
                mItemBinding!!.entity = item
                mItemBinding!!.executePendingBindings()
                Glide.with(mContext).load(item!!.logo).error(R.drawable.icon_team_default).placeholder(R.drawable.icon_team_default).into(mItemBinding!!.ivGroupPic)
                mItemBinding!!.tvAttention.setOnClickListener {
                    if (mCallBack != null){
                        mCallBack!!.cancelAttention(helper.layoutPosition, item)
                    }
                }
                helper.itemView.setOnClickListener {
                    if (mCallBack != null){
                        mCallBack!!.clickItem(item)
                    }
                }
            }
        }

    }

    class OrganizationAttentionAdapter(layoutId : Int, resource : Resources) : BaseQuickAdapter<SelfAttentionEntity, BaseViewHolder>(layoutId){
        private var mCallBack : AttentionCallBack ?= null
        private var mItemBinding : ItemOrganizationAttentionBinding ?= null
        private var resource : Resources = resource

        private var mColorSpan : ForegroundColorSpan = ForegroundColorSpan(resource.getColor(R.color.color_title_medium))

        private var ssb : SpannableStringBuilder ?= null

        fun setCallBack(callBack : AttentionCallBack){
            this.mCallBack = callBack
        }
        override fun convert(helper: BaseViewHolder?, item: SelfAttentionEntity?) {
            mItemBinding = DataBindingUtil.bind(helper!!.itemView)
            if (mItemBinding != null){
                mItemBinding!!.entity = item
                mItemBinding!!.resource = resource
                mItemBinding!!.executePendingBindings()
                Glide.with(mContext).load(item!!.logo).error(R.drawable.icon_organization_default).placeholder(R.drawable.icon_organization_default).into(mItemBinding!!.ivOrganizationPic)
                setColorSpan(resource.getString(R.string.organization_attention_address, if (TextUtils.isEmpty(item.address))  "" else item.address), mItemBinding!!.tvOrganizationAddress)
                setColorSpan(resource.getString(R.string.organization_attention_type, if (TextUtils.isEmpty(item.institutionalTypeName))  "" else item.institutionalTypeName), mItemBinding!!.tvGroupType)
                mItemBinding!!.tvAttention.setOnClickListener {
                    if (mCallBack != null){
                        mCallBack!!.cancelAttention(helper.layoutPosition, item)
                    }
                }
                helper.itemView.setOnClickListener {
                    if (mCallBack != null){
                        mCallBack!!.clickItem(item)
                    }
                }
            }
        }
        private fun setColorSpan(content: String, tv: TextView) {
            ssb = SpannableStringBuilder(content)
            ssb!!.setSpan(mColorSpan, content.indexOf("："), content.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
            tv.text = ssb
        }
    }

    interface AttentionCallBack{
        fun cancelAttention(position : Int, entity: SelfAttentionEntity)
        fun clickItem(entity: SelfAttentionEntity)
    }
}